package com.wrx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wrx.server.config.security.JwtTokenUtil;
import com.wrx.server.mapper.UserMapper;
import com.wrx.server.pojo.RespBean;
import com.wrx.server.pojo.User;
import com.wrx.server.pojo.UserLoginParam;
import com.wrx.server.pojo.UserRegisterParam;
import com.wrx.server.service.IUserService;
import com.wrx.server.util.IDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wrx
 * @since 2021-03-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登陆之后返回token
     *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        System.out.println("gogogogogo");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码输入错误，请重新输入");
        }

        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            System.out.println("用户名或密码不正确");
            return RespBean.error("用户名或密码不正确");
        }

        if (!userDetails.isEnabled()) {
            System.out.println("账号被禁用，请联系管理员！");
            return RespBean.error("账号被禁用，请联系管理员！");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        System.out.println("token :" + token);
        System.out.println("token" + token.getBytes());
        System.out.println("登陆成功");

        User user = getUserByUserName(username);
        user.setPassword("null");

        return RespBean.success("登录成功", tokenMap,user);
    }

    /**
     * 用户注册
     *
     * @param userRegisterParam
     * @return
     */
    @Override
    public RespBean register(UserRegisterParam userRegisterParam, HttpServletRequest request) {

        String captcha = (String) request.getSession().getAttribute("captcha");
        String code = userRegisterParam.getCode();
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码输入错误，请重新输入");
        }

        String checkpassword = userRegisterParam.getCheckpassword();
        String password = userRegisterParam.getPassword();
        //判断密码是否为空
        if ("".equals(checkpassword) || "".equals(password)) {
            return RespBean.error("输入的密码为空，请重新输入");
        }

        //判断sql中是否存在相同的username
        if (userMapper.selUserInfoByUserName(userRegisterParam.getUsername())!=0) {
            return RespBean.error("注册用户名已存在，请重新输入");
        }

        if (password.equals(checkpassword)) {
            //将密码加密为hash形式
            String hashedPassword = passwordEncoder.encode(password);
            userRegisterParam.setPassword(hashedPassword);

            userMapper.insertUserInfo(userRegisterParam);
            return RespBean.success("注册成功！");
        } else {
            return RespBean.error("两次输入的密码不一致");
        }
    }


    /**
     * 根据用户名获取用户
     *
     * @param username
     * @return
     */
    @Override
    public User getUserByUserName(String username) {
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", username)
                .eq("enabled", true));
    }

    @Override
    public User getUserInfo(Principal principal) {
        if (null == principal){
            return null;
        }
        String username = principal.getName();
        User user = this.getUserByUserName(username);
        user.setPassword(null);
        return user;
    }

}
